<template>
  <div>
    <a-button style="margin-bottom: 20px" @click="addFee" type="primary">添加费用</a-button>
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />
    <table-index @loadData="loadData" :table="tableCompulsory">
      <template #expand-icon="{ expanded }">
        <icon-plus-circle style="font-size: 20px; color: #0256ff" v-if="!expanded" />
        <icon-minus-circle style="font-size: 20px; color: #0256ff" v-else />
      </template>
      <template #feeNameSort="{ record }">
        <div v-if="record.mtype == 'MENU'" style="margin-left: 0">{{ record.feeName }}</div>
        <div v-if="record.mtype == 'TERM1'" style="margin-left: 20px">{{ record.feeName }}</div>
      </template>
    </table-index>
    <!-- 添加费用弹框 -->
    <a-modal v-model:visible="feeVisible" width="80vw">
      <template #title> 添加费用 </template>
      <template #footer>
        <a-space>
          <a-button @click="handleFeeCancel">关闭</a-button>
          <a-button type="primary" @click="handleFeeOk">确认</a-button>
        </a-space>
      </template>
      <page-form :model="form" layout="vertical" ref="formRef" class="page-form">
        <div class="mains">
          <div class="mains-tlt">
            <div class="mian-line"></div>
            <text>{{ supplierType == 1 ? '保养' : '' }}{{ supplierType == 2 ? '维修' : '' }}项目</text>
            <div v-if="supplierType == 1 || supplierType == 2" class="choose-mains" @click="chooseMarins"
              >选择{{ supplierType == 1 ? '保养' : '' }}{{ supplierType == 2 ? '维修' : '' }}项目</div
            >
            <div v-if="supplierType == 3" class="choose-mains" @click="addMarins">添加{{ supplierType == 3 ? '年检' : '' }}项目</div>
          </div>
          <page-form-row>
            <div class="mains-form-items">
              <div class="mains-form-item" v-for="(item, index) in form.detailList" :key="item.id">
                <div class="mains-form-tlt" v-if="supplierType == 1 || supplierType == 2">
                  <div class="mains-form-tlt-name">{{ item.itemName }}</div>
                  <div class="main-icon" style="color: #ea0000" @click="deleteMain(item)">
                    <SvgIcon name="main-delete" color="#ea0000" />
                    删除
                  </div>
                </div>
                <div class="mains-form-in">
                  <div class="mains-form-in-c">
                    <page-form-item
                      v-if="supplierType == 3"
                      :field="`detailList[${index}].itemName`"
                      :rules="{ required: true, message: '请输入费用名称' }"
                      label="费用名称"
                      size="1/4"
                    >
                      <i-input placeholder="请输入" v-model="item.itemName" :maxLength="30" />
                    </page-form-item>
                    <page-form-item v-if="supplierType == 1 || supplierType == 2" label="品牌" size="1/5">
                      <i-input placeholder="请输入" v-model="item.brand" :maxLength="30" />
                    </page-form-item>
                    <page-form-item v-if="supplierType == 1 || supplierType == 2" label="单价" size="1/5">
                      <a-input-number
                        :max="99999999.99"
                        :min="0"
                        placeholder="请输入"
                        v-model="item.unitPrice"
                        @blur="count($event, index, 'price')"
                        hide-button
                        :precision="2"
                        :max-length="10"
                      >
                        <template #suffix> 元 </template>
                      </a-input-number>
                    </page-form-item>
                    <page-form-item v-if="supplierType == 1 || supplierType == 2" label="数量" size="1/5">
                      <a-input-number
                        placeholder="请输入"
                        v-model="item.costQuantity"
                        @blur="count($event, index, 'num')"
                        hide-button
                        :precision="0"
                        :max-length="8"
                      >
                        <template #suffix> </template>
                      </a-input-number>
                    </page-form-item>
                    <page-form-item
                      :label="supplierType == 3 ? '金额' : '总价'"
                      :field="`detailList[${index}].amount`"
                      :rules="{ required: true, message: supplierType == 3 ? '请输入金额' : '请输入总价' }"
                      :size="supplierType == 3 ? '1/4' : '1/5'"
                    >
                      <a-input-number
                        placeholder="请输入"
                        v-model="item.amount"
                        @blur="materialPriceCount($event, index, 'materialPrice')"
                        hide-button
                        :precision="2"
                        :max-length="10"
                      >
                        <template #suffix> 元 </template>
                      </a-input-number>
                    </page-form-item>
                    <page-form-item label="备注" :size="supplierType == 3 ? '1/4' : '1/5'">
                      <i-input placeholder="请输入" v-model="item.remark" :maxLength="30" />
                    </page-form-item>
                  </div>
                  <div v-if="supplierType == 3" class="main-icon" style="color: #ea0000" @click="deleteMain(item)">
                    <SvgIcon name="main-delete" color="#ea0000" />
                    删除
                  </div>
                </div>
                <div class="mains-line"></div>
              </div>
            </div>
          </page-form-row>
        </div>
      </page-form>
      <div class="all-count" v-if="form.detailList && form.detailList.length > 0">
        <!-- <icon-info-circle-fill style="font-size: 16px; color: #165dffff" /> -->
        <icon-exclamation-circle style="font-size: 16px; color: #165dffff" />
        <text>合计：</text>
        <span>{{ maintenanceAmount ? maintenanceAmount : '0' }}元</span>
      </div>
    </a-modal>
    <mains ref="maintenance" @saveCheck="getCheck" />
    <fee ref="feepage" @feepageConfirm="feepageConfirm" />
    <mainEditFeeModal ref="maineditfee" @feepageConfirm="feepageConfirm" />
  </div>
</template>

<script setup name="CostConfirmList">
  import mainEditFeeModal from '@/views/editFee/mainFee/index.vue'
  import { ref, onMounted, watch, reactive, computed } from 'vue'
  import { useTable } from '@/hooks/table'
  import { batchAddCarAssetFee, getCarAssetFeeByBusinesId } from '@/api/finance/costConfirm'
  import mains from '@/components/main/mains.vue'
  import fee from '@/views/confirmFee/maintenance/index.vue'
  import { useRoute } from 'vue-router'
  import { usePageDict } from '@/hooks/useDict'
  const dict = usePageDict('carAssetFeeDict')
  const route = useRoute()
  const maineditfee = ref()
  const queryParam = reactive({})
  // 查询条件
  const searchList = computed(() => {
    return [
      // { label: '费用类型', prop: 'feeType', type: 'a-select', options: dict.carAssetFeeTypeEnum },
      { label: '收支类型', prop: 'costType', type: 'a-select', options: dict.costTypeEnum },
      { label: '费用状态', prop: 'feeStatus', type: 'a-select', options: dict.feeStatusEnum },
    ]
  })
  watch(
    () => route.path,
    (to, from) => {
      if (from == '/car-maintenance/editFees' || from == '/car-maintenance/confirmFees') {
        loadData()
      }
    }
  )
  const formRef = ref(null)
  const form = ref({
    detailList: [],
  })
  const feepage = ref(null)
  const feeVisible = ref(false)
  const props = defineProps({
    id: Number,
    supplierType: undefined,
  })
  const addFee = () => {
    feeVisible.value = true
    form.value.detailList = []
  }
  const handleFeeOk = () => {
    console.log('form.value.detailList', form.value.detailList)
    if (!form.value.detailList || form.value.detailList.length == 0) {
      console.log(1)
      return false
    } else {
      console.log(2)
      formRef.value.validate((error) => {
        if (!error) {
          feeVisible.value = false
          // 添加费用
          var params = {
            businesId: props.id,
            id: null,
            feeDetailList: form.value.detailList,
            feeCategory: props.supplierType, //(0 购置费 1保养 2维修 3年检 4违章)
          }
          batchAddCarAssetFee(params).then((res) => {
            console.log(res)
            loadData()
          })
        }
      })
    }
  }
  const handleFeeCancel = () => {
    feeVisible.value = false
  }

  // 计算单个价格
  const count = (e, index) => {
    console.log(form.value.detailList[index].costQuantity)
    form.value.detailList[index].amount = form.value.detailList[index].costQuantity * form.value.detailList[index].unitPrice
    getAllCount()
  }

  // 单个总价输入
  const materialPriceCount = () => {
    maintenanceAmount.value = 0
    getAllCount()
  }

  // 计算总价
  const maintenanceAmount = ref()
  const getAllCount = () => {
    maintenanceAmount.value = 0
    form.value.detailList.forEach((i) => {
      maintenanceAmount.value += i.amount ? i.amount : 0
    })
    console.log('总价', maintenanceAmount.value)
  }

  // 弹窗选择的保养项目回显
  const getCheck = (e) => {
    console.log('弹窗选择的保养项目回显', e)
    console.log('form.value.detailList', form.value.detailList)
    var arr = form.value.detailList
    if (e && e.length) {
      e.forEach((el) => {
        if (arr && arr.length) {
          arr.forEach((ol) => {
            if (el.itemNameId == ol.itemNameId) {
              el = ol
              console.log('ol', ol)
              console.log('el', el)
            }
          })
        }
      })
      console.log('eee2', e)
    }
    form.value.detailList = e
    console.log('eeeee', e)
    getAllCount() //重新计算
  }

  // 选择保养项目(新增/编辑)
  const maintenance = ref(null)
  const chooseMarins = () => {
    maintenance.value.show(form.value.detailList ? form.value.detailList : [], props.supplierType) //(0 购置费 1保养 2维修 3年检 4违章)
  }

  // 添加年检项目
  const addMarins = () => {
    form.value.detailList.push({
      itemName: undefined,
      amount: undefined,
      remark: undefined,
    })
  }

  // 删除保养项目(新增/编辑)
  const deleteMain = (e) => {
    form.value.detailList = form.value.detailList.filter(function (item) {
      return item !== e
    })
    getAllCount() //重新计算
  }

  // table 配置
  const tableCompulsory = useTable({
    pagination: false,
    columns: [
      { title: '费用名称', dataIndex: 'feeName', width: 240, slotName: 'feeNameSort', fixed: 'left' },
      { title: '费用类型', dataIndex: 'feeTypeName' },
      {
        title: '收支类型',
        dataIndex: 'costTypeName',
        width: 100,
      },
      {
        title: '费用金额(元)',
        dataIndex: 'totalAmount',
        width: 110,
      },
      { title: '待结金额(元)', dataIndex: 'outstandingAmount', width: 110 },
      { title: '生成节点', dataIndex: 'createNodeName', width: 100 },
      { title: '生成时间', dataIndex: 'createTime', width: 170 },
      { title: '应结日期', dataIndex: 'dueDate', width: 170, titleTooltipContent: '取自供应商结算配置' },
      { title: '收支方式', dataIndex: 'payTypeName', width: 100 },
      { title: '费用状态', dataIndex: 'feeStatusName', width: 100 },
      { title: '确认时间', dataIndex: 'confirmTime', width: 170 },
      { title: '确认人', dataIndex: 'confirmUserName', width: 100 },
      { title: '费用备注', dataIndex: 'remark' },
      { title: '结算备注', dataIndex: 'settlementRemark' },
    ],
    operates: [
      // 费用分类(0 购置费 1保养 2维修 3年检 4违章)
      {
        label: '确认对账',
        // permission: 'svms:finance:costConfirm.confirm',
        show: (record) => record.level == 1 && (record.feeStatus == 0 || record.feeStatus == 3 || record.feeStatus == 5),
        method: (record) => {
          feepage.value.show([record.id], record)
        },
      },
      {
        label: '修改费用',
        show: (record) => record.level == 1 && (record.feeStatus == 0 || record.feeStatus == 3 || record.feeStatus == 5),
        method: (record) => {
          maineditfee.value.show(record.id, props.supplierType)
        },
      },
    ],
    buttons: [],
    expandable: {},
  })

  // 列表接口调用
  onMounted(() => {
    loadData()
  })
  const loadData = () => {
    const param = {
      businesId: props.id,
      feeCategory: props.supplierType,
    }
    tableCompulsory.tableLoading = true
    getCarAssetFeeByBusinesId(param)
      .then((res) => {
        const result = res.result

        const dataOne = []
        if (result && result.length) {
          result.forEach((i) => {
            if (
              (queryParam.feeType == undefined || queryParam.feeType === i.feeType) &&
              (queryParam.costType == undefined || queryParam.costType === i.costType) &&
              (queryParam.feeStatus == undefined || queryParam.feeStatus === i.feeStatus)
            ) {
              dataOne.push(i)
            }
          })
        }

        setTimeout(() => {
          tableCompulsory.dataList = tabletolist(dataOne)
        }, 0)
      })
      .finally(() => {
        tableCompulsory.tableLoading = false
      })
  }
  // 字段处理
  const tabletolist = (list) => {
    list.forEach((el) => {
      el.mtype = 'MENU'
      el.level = 1
      if (el.feeDetailList && el.feeDetailList.length) {
        el.children = el.feeDetailList
        el.children.forEach((pl) => {
          pl.id = pl.id + 10000 //因折叠根据id问题(父子级id相同)，数据只做展示，故自定义
          pl.mtype = 'TERM1'
          pl.expand = null
          pl.feeName = pl.itemName
          pl.totalAmount = pl.amount
        })
      } else {
        return false
      }
    })
    return list
  }
  // 确认成功
  const feepageConfirm = () => {
    console.log('确认成功')
    loadData()
  }
</script>

<style lang="less" scoped>
  .mains {
    position: relative;
    width: 100%;
    padding: 20px;
    max-height: 500px;
    overflow-y: scroll;
    .mains-tlt {
      font-size: 14px;
      color: #1d2129;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .mian-line {
        width: 3px;
        height: 16px;
        background-color: #165dff;
        margin-right: 8px;
      }
      .choose-mains {
        margin-left: 16px;
        display: inline-block;
        padding: 5px 16px;
        color: #fff;
        font-size: 14px;
        font-weight: 500;
        background: #1890ff;
        border-radius: 2px;
      }
    }
    .mains-items {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-wrap: wrap;
      .mains-item {
        margin-top: 10px;
        margin-right: 8px;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 3px 8px;
        border: 1px solid #e5e6eb;
        border-radius: 2px;
      }
    }
    .mains-form-items {
      margin-top: 16px;
      width: 100%;
      .mains-form-item {
        width: 100%;
        .mains-form-tlt {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          .mains-form-tlt-name {
            color: var(--color-text-1);
            font-weight: 500;
          }
          .main-icon {
            margin-left: 22px;
            cursor: pointer;
          }
        }
        .mains-form-in {
          width: 100%;
          margin-top: 16px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          // .mains-form-initem {
          //   width: 20%;
          //   margin-right: 10px;
          //   display: flex;
          //   flex-direction: column;
          //   justify-content: flex-start;
          //   align-items: flex-start;
          // }
          .mains-form-in-c {
            flex: 1;
            display: flex;
            justify-content: space-between;
            align-items: center;
          }
        }
        .mains-line {
          width: 100%;
          height: 1px;
          background-color: #f2f3f5;
          margin: 20px 0;
        }
      }
    }
  }
  .operate-btn {
    font-size: 14px;
    height: 32px;
    line-height: 32px;
    white-space: nowrap;
    outline: none;
    cursor: pointer;
    user-select: none;
    padding: 0 5px;
    icon {
      margin-right: 8px;
    }
    &.del {
      color: #ea0000;
    }
    &.new {
      color: #165dff;
    }
  }
  .box {
    width: 200px;
    height: 40px;
    border: 1px solid wheat;
  }
  .box:hover {
    transform: scale(1.1);
    transition: transform 0.3s;
    position: relative;
    z-index: 999;
  }
  .quick-search {
    display: flex;
    margin-bottom: 20px;
  }
  .quick-search-item {
    width: 16%;
    height: 62px;
    padding: 9px 0 9px 16px;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #e5e8ef;
  }
  .quick-search-item:hover {
    transform: scale(1.1);
    transition: transform 0.3s;
    position: relative;
    z-index: 999;
  }
  .quick-search-item-checked {
    background: #e8f3ff;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #1890ff;
  }
  .quick-search-item:nth-of-type(n + 2) {
    margin-left: 20px;
  }
  .quick-search-item-label {
    font-size: 12px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #4e5969;
  }
  .quick-search-item-value {
    font-size: 20px;
    font-family: PingFang SC-Semibold, PingFang SC;
    font-weight: 600;
    color: #1d2129;
  }
  .quick-search-item-value-checked {
    color: #1890ff;
  }
  :deep(.arco-table-expand-btn) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  :deep(.arco-table-expand-btn:hover) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  .second-stage {
    width: 200px;
    margin-left: 260px;
  }
  .third-stage {
    width: 200px;
    margin-left: 30px;
  }
  .fee-modal {
  }
  .page-form {
    margin: 0;
    // padding: 0 60px;
    :deep(.arco-row) {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }
    :deep(.arco-modal-body) {
      padding: 10px 80px !important;
    }
    :deep(.arco-col) {
      padding: 0 10px !important;
    }
  }
  .all-count {
    float: right;
    font-weight: 600;
    color: #1d2129;
    font-size: 14px;
    span {
      font-size: 16px;
      color: #165dff;
    }
  }
</style>
